package com.agent.demo;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import java.util.List;
import java.util.Scanner;

public class AttachMain {
    public static void main(String[] args) {
        try {

            List<VirtualMachineDescriptor> list = VirtualMachine.list();
            for (VirtualMachineDescriptor virtualMachineDescriptor : list) {
                System.out.println(virtualMachineDescriptor.id() + " " + virtualMachineDescriptor.displayName());
            }

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入目标程序PID:");
            int pid = scanner.nextInt();
            VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
            vm.loadAgent("agent-agentmain-1.0-SNAPSHOT-jar-with-dependencies.jar", "agentmain");
            System.out.println(pid + " attach 成功, 输入 exit 退出.");
            // 防止程序结束
            while (!"exit".equals(scanner.nextLine())) {
                System.out.println("请输入:");
            }
            vm.detach();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
